package com.keepers.repair.fragment

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.keepers.repair.R
import com.keepers.repair.adapter.ChatHistoryAdapter
import com.keepers.repair.model.ChatHistoryItemModel
import com.keepers.repair.utils.Api
import com.keepers.repair.utils.getUser
import org.jetbrains.anko.find


class ChatHistoryFragment : Fragment() {

    private lateinit var refreshLayout: SwipeRefreshLayout
    private lateinit var recyclerView: RecyclerView

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.fragment_chat_history, container, false)
        refreshLayout = view.find(R.id.chat_history_refresh_layout)
        recyclerView = view.find(R.id.chat_history_recycler_view)

        refreshLayout.setOnRefreshListener(this::refreshList)
        recyclerView.layoutManager = LinearLayoutManager(context)
        refreshList()

        return view
    }

    private fun refreshList() {
        refreshLayout.isRefreshing = true
        val userManager = getUser(context!!)
        userManager?.apply {
            Api.getChatHistory(Gid, GroupGid!!) { chatHistory ->
                recyclerView.adapter = ChatHistoryAdapter(chatHistory.sortedBy(ChatHistoryItemModel::ChattingDate))
                refreshLayout.isRefreshing = false
            }
        }
    }
}
